#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QHostAddress>
#include <string>
using namespace std;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("TCP - 客户端");

    ui->ip->setText("127.0.0.1");
    ui->port->setText("8989");
    ui->disconnect->setEnabled(false);

    m_interface = new Interface;

    m_tcp = new QTcpSocket(this);
    connect(m_tcp, &QTcpSocket::readyRead, [=]()
    {
        QByteArray recvMsg = m_tcp->readAll();

        // 解密
        string ret = m_interface->decryptString(QString(recvMsg).toStdString());
        ui->record->append("服务器Say: " + QString::fromStdString(ret));
    });
    connect(m_tcp, &QTcpSocket::connected, this, [=]()
    {
        ui->record->append("恭喜, 连接服务器成功!!!");
        m_status->setPixmap(QPixmap(":/connect.png").scaled(20, 20));
    });
    connect(m_tcp, &QTcpSocket::disconnected, this, [=]()
    {
        if(ui)
        {
            ui->record->append("服务器已经断开了连接, ...");
            ui->connectServer->setEnabled(true);
            ui->disconnect->setEnabled(false);
            m_status->setPixmap(QPixmap(":/disconnect.png").scaled(20, 20));
        }
    });

    m_status = new QLabel;
    m_status->setPixmap(QPixmap(":/disconnect.png").scaled(20, 20));
    ui->statusBar->addWidget(new QLabel("连接状态: "));
    ui->statusBar->addWidget(m_status);
}

MainWindow::~MainWindow()
{
    delete ui;
    ui = nullptr;
}

void MainWindow::on_connectServer_clicked()
{
    QString ip = ui->ip->text();
    unsigned short port = ui->port->text().toInt();
    m_tcp->connectToHost(QHostAddress(ip), port);
    ui->connectServer->setEnabled(false);
    ui->disconnect->setEnabled(true);
}

void MainWindow::on_sendMsg_clicked()
{
    QString sendMsg = ui->msg->toPlainText();
    // 加密
    string tmp = m_interface->encryptString(sendMsg.toStdString());
    m_tcp->write(tmp.data());
    ui->record->append("服务器Say: " + sendMsg);
    ui->msg->clear();
}

void MainWindow::on_disconnect_clicked()
{
    m_tcp->close();
    ui->connectServer->setEnabled(true);
    ui->disconnect->setEnabled(false);
}
